<template>
  <div id="configuration">
    <!-- Tab header -->
    <div class="tab-header" style="position: relative">
      <template v-for="(item, index) in options">
        <div
          :class="{ is_active: activeName === item.value }"
          @click="handleClick(item)"
          v-if="hasPermission(item.code)"
        >
          {{ item.name }}
        </div>
      </template>
    </div>

    <!-- 表单区域 -->
    <Card class="form-content">
      <!-- 配置管理页面 -->
      <template v-if="activeName === 'config'">
        <Form
          ref="formDialog"
          :model="dialogForm"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
        >
          <FormItem label="服务配置管理">
            <div v-if="loginStatus == '0'" class="statusbox lineBox">
              <span class="statusline lineed">
                <!-- 需提前注册 CheckOutlined 图标 -->
                <CheckOutlined />
              </span>
              <span class="statustxt">已连接</span>
            </div>
            <div v-else class="statusbox unlineBox">
              <span class="statusline unline">
                <CloseOutlined />
              </span>
              <span class="statustxt">断开</span>
            </div>
          </FormItem>

          <FormItem label="管理服务内网IP地址" name="manageServerInnerIp">
            <Input
              v-model:value="dialogForm.manageServerInnerIp"
              :maxlength="50"
              placeholder="请输入管理服务内网IP地址"
            />
          </FormItem>

          <FormItem label="接口服务端口" name="interfaceServerPort">
            <Input
              v-model:value="dialogForm.interfaceServerPort"
              :maxlength="50"
              placeholder="请输入接口服务端口"
            />
          </FormItem>

          <FormItem label="状态服务端口" name="statusServerPort">
            <Input
              v-model:value="dialogForm.statusServerPort"
              :maxlength="50"
              placeholder="请输入状态服务端口"
            />
          </FormItem>

          <FormItem label="发布服务内网IP地址" name="publishServerInnerIp">
            <Input
              v-model:value="dialogForm.publishServerInnerIp"
              :maxlength="50"
              placeholder="请输入发布服务内网IP地址"
            />
          </FormItem>

          <FormItem label="业务服务端口" name="businessServerInnerPort">
            <Input
              v-model:value="dialogForm.businessServerInnerPort"
              :maxlength="50"
              placeholder="请输入业务服务端口"
            />
          </FormItem>

          <FormItem label="管理服务端口" name="manageServerPort">
            <Input
              v-model:value="dialogForm.manageServerPort"
              :maxlength="50"
              placeholder="请输入管理服务端口"
            />
          </FormItem>

          <FormItem label="发布服务外网IP地址" name="publishServerOuterIp">
            <Input
              v-model:value="dialogForm.publishServerOuterIp"
              :maxlength="50"
              placeholder="请输入发布服务外网IP地址"
            />
          </FormItem>

          <FormItem label="业务服务端口" name="businessServerOuterPort">
            <Input
              v-model:value="dialogForm.businessServerOuterPort"
              :maxlength="50"
              placeholder="请输入业务服务端口"
            />
          </FormItem>
        </Form>
      </template>

      <!-- 通用设置页面 -->
      <template v-else-if="activeName === 'common'">
        <Form
          class="pb-2"
          ref="common"
          :model="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
        >
          <FormItem>
            <template #label>
              最大报文大小
              <Tooltip
                title="允许的最大 MQTT 报文大小，超出此大小后将断开当前客户端连接。"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="max_packet_size_num" placeholder="">
              <template #addonAfter>
                <Select v-model:value="size" class="append-select">
                  <SelectOption value="MB">MB</SelectOption>
                  <SelectOption value="GB">GB</SelectOption>
                  <SelectOption value="KB">KB</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem label="最大Qos" name="max_qos_allowed">
            <Select v-model:value="form.max_qos_allowed">
              <SelectOption :value="0">0</SelectOption>
              <SelectOption :value="1">1</SelectOption>
              <SelectOption :value="2">2</SelectOption>
            </Select>
          </FormItem>

          <FormItem label="最大客户端 ID 长度" name="max_clientid_len">
            <Input v-model:value="form.max_clientid_len" placeholder="" />
          </FormItem>

          <FormItem label="最大主题层级" name="max_topic_levels">
            <Input v-model:value="form.max_topic_levels" placeholder="" />
          </FormItem>

          <FormItem label="最大主题别名数" name="max_topic_alias">
            <Input v-model:value="form.max_topic_alias" placeholder="" />
          </FormItem>

          <FormItem label="允许通配符订阅" name="wildcard_subscription">
            <Switch v-model:checked="form.wildcard_subscription" />
          </FormItem>

          <FormItem label="允许共享订阅" name="shared_subscription">
            <Switch v-model:checked="form.shared_subscription" />
          </FormItem>

          <FormItem label="允许排它订阅" name="exclusive_subscription">
            <Switch v-model:checked="form.exclusive_subscription" />
          </FormItem>

          <FormItem>
            <template #label>
              启用保留消息
              <Tooltip title="是否启用对 MQTT 保留消息的支持。">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="form.retain_available" />
          </FormItem>

          <FormItem>
            <template #label>
              忽略循环投递
              <Tooltip
                title="设置由 MQTT v3.1.1/v3.1.0 客户端发布的消息是否将转发给其本身；类似 MQTT 5.0 协议中的 No Local 选项。"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="form.ignore_loop_deliver" />
          </FormItem>

          <FormItem>
            <template #label>
              严格模式
              <Tooltip
                title="是否以严格模式解析 MQTT 消息。严格模式下，如客户端 ID、主题名称等中包含无效 utf8 字符串，连接将被断开"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="form.strict_mode" />
          </FormItem>

          <FormItem>
            <template #label>
              响应信息
              <Tooltip
                title="UTF-8 字符串，用于指定返回给客户端的响应主题，如 reqrsp/，此时请求和应答客户端都需要使用 reqrsp/ 前缀的主题来完成通讯。如希望禁用此功能，请在下方的文字框中输入；仅适用于 MQTT 5.0 客户端。"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="form.response_information" placeholder="" />
          </FormItem>

          <FormItem>
            <template #label>
              Keep Alive 倍数
              <Tooltip
                title="Keep-Alive Timeout = Keep-Alive Interval × Keep-Alive Multiplier，根据 MQTT 5.0，默认值为1.5。例如，如果 Keep-Alive interval 为 10 秒，那么乘以 1.5 的倍数，将产生 15 秒的超时。将倍数值增加到 2，超时将延长到 20 秒。"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="form.keepalive_multiplier" placeholder="" />
          </FormItem>

          <FormItem label="服务端 Keep Alive" name="server_keepalive">
            <Switch
              v-model:checked="server_keepalive"
              @change="handleKeepalive"
            />

            <FormItemRest v-show="form.server_keepalive !== 'disabled'">
              <Input class="mt-2" v-model:value="form.server_keepalive" />
            </FormItemRest>
          </FormItem>

          <FormItem>
            <template #label>
              使用用户名作为客户端 ID
              <Tooltip
                title="是否使用用户名作为客户端 ID。作用时间晚于 对端证书作为用户名 和 对端证书作为客户端 ID。"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="form.use_username_as_clientid" />
          </FormItem>

          <FormItem>
            <template #label>
              使用对端证书作为用户名
              <Tooltip
                title="使用对端证书中的 CN、DN 字段或整个证书内容来作为用户名；仅适用于 TLS 连接。支持：cn、dn、crt、pem、md5"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Select v-model:value="form.peer_cert_as_username" placeholder="">
              <SelectOption
                v-for="(item, index) in peerOptions"
                :key="index"
                :value="item.value"
              >
                {{ item.name }}
              </SelectOption>
            </Select>
          </FormItem>

          <FormItem>
            <template #label>
              使用对端证书作为客户端ID
              <Tooltip
                title="使用对端证书中的 CN、DN 字段或整个证书内容来作为客户端 ID；仅适用于 TLS 连接。支持：cn、dn、crt、pem、md5"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Select v-model:value="form.peer_cert_as_clientid" placeholder="">
              <SelectOption
                v-for="(item, index) in peerOptions"
                :key="index"
                :value="item.value"
              >
                {{ item.name }}
              </SelectOption>
            </Select>
          </FormItem>

          <FormItem>
            <template #label>
              空闲超时
              <Tooltip
                title="设置连接被断开或进入休眠状态前的等待时间。注意：请合理设置该参数值，如等待时间设置过长可能造成系统资源浪费。"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="idle_timeout" @change="handleTimeout" />
            <FormItemRest v-if="form.idle_timeout !== 'infinity'">
              <Input
                class="block mt-2"
                v-model:value="idle_timeout_num"
                placeholder=""
              >
                <template #addonAfter>
                  <Select
                    v-model:value="time"
                    class="append-select"
                    placeholder="请选择"
                  >
                    <SelectOption value="ms">毫秒</SelectOption>
                    <SelectOption value="s">秒</SelectOption>
                    <SelectOption value="m">分钟</SelectOption>
                    <SelectOption value="h">小时</SelectOption>
                  </Select>
                </template>
              </Input>
            </FormItemRest>
          </FormItem>
        </Form>
      </template>

      <!-- 会话设置页面 -->
      <template v-else-if="activeName === 'session'">
        <Form
          class="pb-2"
          ref="session"
          :model="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
        >
          <FormItem>
            <template #label>
              会话过期间隔
              <Tooltip
                title="指定会话将在连接断开后多久过期，仅适用于非 MQTT 5.0 连接"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="session_expiry_interval" placeholder="">
              <template #addonAfter>
                <Select
                  v-model:value="intervalTime"
                  class="append-select"
                  placeholder="请选择"
                >
                  <SelectOption value="ms">毫秒</SelectOption>
                  <SelectOption value="s">秒</SelectOption>
                  <SelectOption value="m">分钟</SelectOption>
                  <SelectOption value="h">小时</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem>
            <template #label>
              最大订阅数量
              <Tooltip title="允许每个客户端建立的最大订阅数量">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="max_subscriptions"
              @change="handleSubscrip"
            />
            <FormItemRest v-if="form.max_subscriptions !== 'infinity'">
              <Input
                class="mt-2"
                v-model:value="form.max_subscriptions"
                placeholder=""
              />
            </FormItemRest>
          </FormItem>

          <FormItem>
            <template #label>
              升级Qos
              <Tooltip
                title="投递消息时是否根据订阅主题时的 QoS 来强制提升派发消息的 QoS"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="form.upgrade_qos" />
          </FormItem>

          <FormItem>
            <template #label>
              最大飞行窗口
              <Tooltip
                title="完成应答前最多允许同时投递的 QoS 1 和 QoS 2 消息数量"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="form.max_inflight" placeholder="" />
          </FormItem>

          <FormItem>
            <template #label>
              消息重试间隔
              <Tooltip title="QoS 1/2 消息的重新投递间隔">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="retry_interval" placeholder="">
              <template #addonAfter>
                <Select
                  v-model:value="retryTime"
                  class="append-select"
                  placeholder="请选择"
                >
                  <SelectOption value="ms">毫秒</SelectOption>
                  <SelectOption value="s">秒</SelectOption>
                  <SelectOption value="m">分钟</SelectOption>
                  <SelectOption value="h">小时</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem>
            <template #label>
              最大待发PUBREL数量
              <Tooltip title="指定未收到 PUBREL 且未超时的最大 QoS 2 消息数量">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="max_awaiting_rel" @change="handleAwait" />
            <FormItemRest v-if="form.max_awaiting_rel !== 'infinity'">
              <Input
                class="mt-2"
                v-model:value="form.max_awaiting_rel"
                placeholder=""
              />
            </FormItemRest>
          </FormItem>

          <FormItem>
            <template #label>
              最大PUBREL等待时长
              <Tooltip
                title="对于未收到 PUBREL 的 QoS 2 消息，指定等待重传的时间"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="await_rel_timeout" placeholder="">
              <template #addonAfter>
                <Select
                  v-model:value="awaitTime"
                  class="append-select"
                  placeholder="请选择"
                >
                  <SelectOption value="ms">毫秒</SelectOption>
                  <SelectOption value="s">秒</SelectOption>
                  <SelectOption value="m">分钟</SelectOption>
                  <SelectOption value="h">小时</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem>
            <template #label>
              最大消息队列长度
              <Tooltip
                title="持久客户端断开连接或飞行窗口已满时允许排队的最大消息数量"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="max_mqueue_len" @change="hadnleMqueue" />
            <FormItemRest v-if="form.max_mqueue_len !== 'infinity'">
              <Input
                class="mt-2"
                v-model:value="form.max_mqueue_len"
                placeholder=""
              />
            </FormItemRest>
          </FormItem>

          <FormItem>
            <template #label>
              主题优先级
              <Tooltip
                title="指定主题优先级（范围：disabled 或 [1-255]），示例：{topic/1: 10, topic/2: 8}"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="mqueue_priorities"
              @change="handlePriorities"
            />
            <FormItemRest v-if="form.mqueue_priorities !== 'disabled'">
              <Input
                class="mt-2"
                v-model:value="form.mqueue_priorities"
                placeholder=""
              />
            </FormItemRest>
          </FormItem>

          <FormItem label="默认主题优先级" name="mqueue_default_priority">
            <Select v-model:value="form.mqueue_default_priority">
              <SelectOption value="highest">highest</SelectOption>
              <SelectOption value="lowest">lowest</SelectOption>
            </Select>
          </FormItem>

          <FormItem>
            <template #label>
              存储 QoS 0 消息
              <Tooltip title="断开连接但会话保持期间是否存储 QoS 0 消息">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="form.mqueue_store_qos0" />
          </FormItem>
        </Form>
      </template>

      <!-- 消息设置页面 -->
      <template v-else-if="activeName === 'msg'">
        <Form
          ref="msg"
          :model="messageForm"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
        >
          <FormItem>
            <template #label>
              启用保留消息
              <Tooltip title="打开或关闭保留消息功能，停用后不会清除已保留消息">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch v-model:checked="messageForm.enable" />
          </FormItem>

          <FormItem>
            <template #label>
              存储类型
              <Tooltip title="后端类型">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Select v-model:value="messageForm.backend.type">
              <SelectOption value="built_in_database">内置数据库</SelectOption>
            </Select>
          </FormItem>

          <FormItem>
            <template #label>
              存储方式
              <Tooltip title="选择消息存储在磁盘还是内存中">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Select v-model:value="messageForm.backend.storage_type">
              <SelectOption value="ram">ram</SelectOption>
              <SelectOption value="disc">disc</SelectOption>
            </Select>
          </FormItem>

          <FormItem>
            <template #label>
              最大保留消息数
              <Tooltip title="消息保留数量上限，0 表示无限">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="max_retained_messages"
              @change="handleRetained"
            />
            <FormItemRest
              v-if="messageForm.backend.max_retained_messages !== '0'"
            >
              <Input
                class="mt-2"
                v-model:value="messageForm.backend.max_retained_messages"
                placeholder=""
              />
            </FormItemRest>
          </FormItem>

          <FormItem>
            <template #label>
              最大消息负载大小
              <Tooltip title="保留消息的最大长度">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="max_payload_size" placeholder="">
              <template #addonAfter>
                <Select
                  v-model:value="payloadSize"
                  class="append-select"
                  placeholder="请选择"
                >
                  <SelectOption value="KB">KB</SelectOption>
                  <SelectOption value="MB">MB</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem>
            <template #label>
              消息过期间隔
              <Tooltip title="消息保留时间，0 代表永久保留">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="msg_expiry_interval"
              @change="hadnleExpiry"
            />
            <FormItemRest v-if="expiry_interval !== '0'">
              <Input
                class="block mt-2"
                v-model:value="expiry_interval"
                placeholder=""
              >
                <template #addonAfter>
                  <Select
                    v-model:value="expiryTime"
                    class="append-select"
                    placeholder="请选择"
                  >
                    <SelectOption value="ms">毫秒</SelectOption>
                    <SelectOption value="s">秒</SelectOption>
                    <SelectOption value="m">分钟</SelectOption>
                    <SelectOption value="h">小时</SelectOption>
                  </Select>
                </template>
              </Input>
            </FormItemRest>
          </FormItem>

          <FormItem>
            <template #label>
              消息清理间隔
              <Tooltip title="消息清理间隔，0 代表不进行清理">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="msg_clear_interval"
              @change="hadnleClear"
            />
            <FormItemRest v-if="clear_interval !== '0'">
              <Input
                class="block mt-2"
                v-model:value="clear_interval"
                placeholder=""
              >
                <template #addonAfter>
                  <Select
                    v-model:value="clearTime"
                    class="append-select"
                    placeholder="请选择"
                  >
                    <SelectOption value="ms">毫秒</SelectOption>
                    <SelectOption value="s">秒</SelectOption>
                    <SelectOption value="m">分钟</SelectOption>
                    <SelectOption value="h">小时</SelectOption>
                  </Select>
                </template>
              </Input>
            </FormItemRest>
          </FormItem>
        </Form>
      </template>

      <!-- 主题设置页面 -->
      <template v-else>
        <Form
          ref="theme"
          :model="themeForm"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
        >
          <FormItem>
            <template #label>
              消息发布周期
              <Tooltip title="发送 $SYS 主题的间隔时间">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="sys_msg_interval" placeholder="">
              <template #addonAfter>
                <Select
                  v-model:value="msgTime"
                  class="append-select"
                  placeholder="请选择"
                >
                  <SelectOption value="s">秒</SelectOption>
                  <SelectOption value="m">分钟</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem>
            <template #label>
              心跳周期
              <Tooltip
                title="发送心跳系统消息的间隔时间，包括： $SYS/brokers/&lt;node&gt;/uptime 与 $SYS/brokers/&lt;node&gt;/datetime"
              >
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Input v-model:value="sys_heartbeat_interval" placeholder="">
              <template #addonAfter>
                <Select
                  v-model:value="heartTime"
                  class="append-select"
                  placeholder="请选择"
                >
                  <SelectOption value="s">秒</SelectOption>
                  <SelectOption value="m">分钟</SelectOption>
                </Select>
              </template>
            </Input>
          </FormItem>

          <FormItem>
            <template #label>
              客户端已连接提醒
              <Tooltip title="是否开启客户端已连接事件消息">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="themeForm.sys_event_messages.client_connected"
            />
          </FormItem>

          <FormItem>
            <template #label>
              客户端断开连接提醒
              <Tooltip title="是否开启客户端已断开连接事件消息">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="themeForm.sys_event_messages.client_disconnected"
            />
          </FormItem>

          <FormItem>
            <template #label>
              客户端订阅提醒
              <Tooltip title="是否开启客户端成功订阅主题的事件消息">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="themeForm.sys_event_messages.client_subscribed"
            />
          </FormItem>

          <FormItem>
            <template #label>
              客户端取消订阅提醒
              <Tooltip title="是否开启客户端取消订阅主题的事件消息">
                <QuestionCircleOutlined />
              </Tooltip>
            </template>
            <Switch
              v-model:checked="themeForm.sys_event_messages.client_unsubscribed"
            />
          </FormItem>
        </Form>
      </template>
    </Card>

    <!-- 底部操作按钮 -->
    <div class="dialog-footer" style="text-align: right; margin-top: 16px">
      <Button v-if="activeName == 'config'" @click="handleSubmit">
        提交
      </Button>
      <Button
        v-if="activeName != 'config' && loginStatus == '0'"
        @click="submitForm"
      >
        保存修改
      </Button>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { hasPermission } from '@/permission';
import {
  CheckOutlined,
  CloseOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons-vue';
import {
  Button,
  Card,
  Form,
  FormItem,
  FormItemRest,
  Input,
  Row,
  Select,
  SelectOption,
  Switch,
  Tooltip,
  message,
} from 'ant-design-vue';
import {
  add,
  detail,
  getCommonConfig,
  getRetainer,
  getSysTopic,
  upadteRetainer,
  update,
  updateCommonConfig,
  updateSysTopic,
} from '@/api/server';

// ---------------------
// 响应式数据
// ---------------------
const activeName = ref('config');
const form = reactive({});
const messageForm = reactive({ backend: {} });
const themeForm = reactive({ sys_event_messages: {} });

const server_keepalive = ref(false);
const max_packet_size_num = ref(null);
const idle_timeout = ref(false);
const idle_timeout_num = ref(null);
const max_subscriptions = ref(false);
const session_expiry_interval = ref(null);
const retry_interval = ref(null);
const await_rel_timeout = ref(null);
const max_payload_size = ref(null);
const max_awaiting_rel = ref(false);
const max_mqueue_len = ref(false);
const mqueue_priorities = ref(false);
const max_retained_messages = ref(null);
const msg_expiry_interval = ref(false);
const expiry_interval = ref(null);
const msg_clear_interval = ref(false);
const clear_interval = ref(null);
const sys_msg_interval = ref(null);
const sys_heartbeat_interval = ref(null);

const options = ref([
  { name: '服务配置', value: 'config', code: 'serverConfig:serviceConfig' },
  { name: '通用', value: 'common', code: 'serverConfig:universality' },
  { name: '会话', value: 'session', code: 'serverConfig:conversation' },
  { name: '保留消息', value: 'msg', code: 'serverConfig:retain:message' },
  { name: '系统主题', value: 'theme', code: 'serverConfig:system:theme	' },
]);

const peerOptions = ref([
  { name: 'disabled', value: 'disabled' },
  { name: 'cn', value: 'cn' },
  { name: 'dn', value: 'dn' },
  { name: 'crt', value: 'crt' },
  { name: 'pem', value: 'pem' },
  { name: 'md5', value: 'md5' },
]);

const configId = ref('');
const size = ref('MB');
const time = ref('ms');
const intervalTime = ref('ms');
const retryTime = ref('ms');
const awaitTime = ref('ms');
const payloadSize = ref('MB');
const expiryTime = ref('ms');
const clearTime = ref('ms');
const msgTime = ref('s');
const heartTime = ref('s');

const elrowGutter = ref(0);
const lftSpan = ref(4);
const rgtSpan = ref(8);
const isShow = ref(true);
const heights = ref(0);
const loginStatus = ref('');

// 表单数据
const dialogForm = reactive({
  configId: '', // 主键
  manageServerInnerIp: '', // 管理服务内网 ip 地址
  interfaceServerPort: '', // 接口服务端口
  statusServerPort: '', // 状态服务端口
  publishServerInnerIp: '', // 发布服务内网 ip 地址
  businessServerInnerPort: '', // 业务服务端口(内网)
  manageServerPort: '', // 管理服务端口
  publishServerOuterIp: '', // 发布服务外网 ip 地址
  businessServerOuterPort: '', // 业务服务端口(外网)
});

// 表单校验规则（如使用 UI 组件的表单校验，可传入此对象）
const rules = reactive({
  manageServerInnerIp: [
    { required: true, message: '请输入管理服务内网ip地址', trigger: 'blur' },
  ],
  interfaceServerPort: [
    { required: true, message: '请输入接口服务端口', trigger: 'blur' },
  ],
  statusServerPort: [
    { required: true, message: '请输入状态服务端口', trigger: 'blur' },
  ],
  publishServerInnerIp: [
    { required: true, message: '请输入发布服务内网ip地址', trigger: 'blur' },
  ],
  businessServerInnerPort: [
    { required: true, message: '请输入业务服务端口(内网)', trigger: 'blur' },
  ],
  manageServerPort: [
    { required: true, message: '请输入管理服务端口', trigger: 'blur' },
  ],
  publishServerOuterIp: [
    { required: true, message: '请输入发布服务外网ip地址', trigger: 'blur' },
  ],
  businessServerOuterPort: [
    { required: true, message: '请输入业务服务端口(外网)', trigger: 'blur' },
  ],
});

// 如果需要表单验证，请为表单组件绑定 ref
const formDialog = ref(null);

// ---------------------
// 方法定义
// ---------------------

// 修改按钮操作：调用 detail 接口并将返回的数据复制到 dialogForm 中
function handleUpdate(flag = true) {
  detail().then((response) => {
    loginStatus.value = response.data.loginStatus;
    console.log(response, 'response');
    for (const key in dialogForm) {
      dialogForm[key] = response.data[key];
    }
  });
}

// 提交表单（调用 update 或 add 接口）
function handleSubmit() {
  formDialog.value.validate((valid) => {
    if (valid) {
      if (dialogForm.configId) {
        update(dialogForm).then(() => {
          handleUpdate();
          message.success('修改成功');
        });
      } else {
        add(dialogForm).then(() => {
          handleUpdate();
          message.success('新增成功');
        });
      }
    }
  });
}

// 获取通用配置
async function _getcommonConfig() {
  const res = await getCommonConfig();
  Object.assign(form, res.data.mqtt); // 合并到已存在的响应式对象
  // for (const key in res.data.mqtt) {
  //   form[key] = res.data.mqtt[key];
  // }
  if (form.server_keepalive != 'disabled') {
    server_keepalive.value = true;
  }
  size.value = form.max_packet_size.slice(-2);
  max_packet_size_num.value = form.max_packet_size.slice(0, -2);

  if (form.idle_timeout != 'infinity') {
    idle_timeout.value = true;
    time.value = extractMsShm(form.idle_timeout);
    idle_timeout_num.value = extractExcept(form.idle_timeout);
  }
  if (form.max_subscriptions != 'infinity') {
    max_subscriptions.value = false;
  }
  if (form.max_awaiting_rel != 'infinity') {
    max_awaiting_rel.value = true;
  }
  if (form.max_mqueue_len != 'infinity') {
    max_mqueue_len.value = true;
  }
  if (form.mqueue_priorities != 'disabled') {
    mqueue_priorities.value = true;
  }

  intervalTime.value = extractMsShm(form.session_expiry_interval);
  session_expiry_interval.value = extractExcept(form.session_expiry_interval);
  retryTime.value = extractMsShm(form.retry_interval);
  retry_interval.value = extractExcept(form.retry_interval);
  awaitTime.value = extractMsShm(form.await_rel_timeout);
  await_rel_timeout.value = extractExcept(form.await_rel_timeout);
  console.log(form.max_subscriptions, 'getCommonConfig');
  console.log(res, 'res');
}

// 获取保留消息配置
async function getmessageConfig() {
  const res = await getRetainer();
  Object.assign(messageForm, res.data);
  console.log(messageForm, 'messageForm');
  if (messageForm.backend.max_retained_messages != 0) {
    max_retained_messages.value = true;
  }
  payloadSize.value = messageForm.max_payload_size.slice(-2);
  max_payload_size.value = messageForm.max_payload_size.slice(0, -2);

  expiryTime.value = extractMsShm(messageForm.msg_expiry_interval);
  expiry_interval.value = extractExcept(messageForm.msg_expiry_interval);
  if (expiry_interval.value != '0') {
    msg_expiry_interval.value = true;
  }

  clearTime.value = extractMsShm(messageForm.msg_clear_interval);
  clear_interval.value = extractExcept(messageForm.msg_clear_interval);
  if (clear_interval.value != '0') {
    msg_clear_interval.value = true;
  }
  console.log(res, 'getRetainer');
}

// 获取系统主题配置
async function getthemeConfig() {
  const res = await getSysTopic();
  Object.assign(themeForm, res.data);
  msgTime.value = extractMsShm(themeForm.sys_msg_interval);
  sys_msg_interval.value = extractExcept(themeForm.sys_msg_interval);
  heartTime.value = extractMsShm(themeForm.sys_heartbeat_interval);
  sys_heartbeat_interval.value = extractExcept(
    themeForm.sys_heartbeat_interval,
  );
}

// 以下为各个配置项中开关（Switch）操作的响应函数
function handleKeepalive(e) {
  if (!e) {
    form.server_keepalive = 'disabled';
  } else {
    form.server_keepalive = '';
  }
}

function handleTimeout(e) {
  if (e) {
    idle_timeout_num.value = '';
    form.idle_timeout = '';
  } else {
    form.idle_timeout = 'infinity';
  }
}

function handleSubscrip(e) {
  if (e) {
    form.max_subscriptions = '';
  } else {
    form.max_subscriptions = 'infinity';
  }
}

function handleAwait(e) {
  if (e) {
    form.max_awaiting_rel = '';
  } else {
    form.max_awaiting_rel = 'infinity';
  }
}

function hadnleMqueue(e) {
  if (e) {
    form.max_mqueue_len = '';
  } else {
    form.max_mqueue_len = 'infinity';
  }
}

function handlePriorities(e) {
  if (!e) {
    form.mqueue_priorities = 'disabled';
  } else {
    form.mqueue_priorities = '';
  }
}

function handleRetained(e) {
  if (e != '0') {
    messageForm.backend.max_retained_messages = '';
  } else {
    messageForm.backend.max_retained_messages = 0;
  }
}

function hadnleExpiry(e) {
  if (!e) {
    expiry_interval.value = '0';
  } else {
    expiry_interval.value = '';
  }
}

function hadnleClear(e) {
  if (!e) {
    clear_interval.value = '0';
  } else {
    clear_interval.value = '';
  }
}

// 根据选项卡切换加载不同配置
function handleClick(e) {
  activeName.value = e.value;
  console.log(loginStatus.value, e.value, 'loginStatus.value');
  if (loginStatus.value == '0') {
    if (e.value == 'config') {
      handleUpdate();
    } else if (e.value == 'common' || e.value == 'session') {
      console.log(e.value, 'e.value');
      _getcommonConfig();
    } else {
      if (e.value == 'msg') {
        getmessageConfig();
      } else if (e.value == 'theme') {
        getthemeConfig();
      }
    }
  }
}

// 保存修改：根据当前 activeName 提交不同接口
const submitForm = () => {
  if (activeName.value === 'msg') {
    messageForm.msg_expiry_interval = expiry_interval.value + expiryTime.value;
    messageForm.msg_clear_interval = clear_interval.value + clearTime.value;
    messageForm.max_payload_size = max_payload_size.value + payloadSize.value;
    upadteRetainer(messageForm).then(() => {
      message.success('保存成功');
    });
  } else if (activeName.value === 'theme') {
    themeForm.sys_msg_interval = sys_msg_interval.value + msgTime.value;
    themeForm.sys_heartbeat_interval =
      sys_heartbeat_interval.value + heartTime.value;
    updateSysTopic(themeForm).then(() => {
      message.success('保存成功');
    });
  } else {
    form.max_packet_size_num = max_packet_size_num.value + size.value;
    if (form.idle_timeout != 'infinity')
      form.idle_timeout = idle_timeout_num.value + time.value;
    form.session_expiry_interval =
      session_expiry_interval.value + intervalTime.value;
    form.retry_interval = retry_interval.value + retryTime.value;
    form.await_rel_timeout = await_rel_timeout.value + awaitTime.value;
    updateCommonConfig(form).then(() => {
      message.success('保存成功');
    });
  }
};

// 辅助方法：提取字符串中单位部分（如 "ms", "s", "m", "h"）
function extractMsShm(input) {
  const regex = /[mssh]/gi;
  const matches = input.match(regex);
  return matches ? matches.join('') : '';
}

// 辅助方法：提取除单位之外的数字部分
function extractExcept(str) {
  const regex = /[^ms,h,m,s]+/g;
  const matches = str.match(regex);
  return matches ? matches.join('') : '';
}

// ---------------------
// 生命周期钩子
// ---------------------
onMounted(() => {
  handleUpdate();
  const temnum = 210;
  heights.value = window.innerHeight - temnum;
  window.addEventListener('resize', resizeHandler);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler);
});

function resizeHandler() {
  const temnum = 210;
  heights.value = window.innerHeight - temnum;
}
</script>

<style lang="scss" scoped>
#configuration {
  padding: 20px;

  .tab-header {
    position: relative;
    display: inline-block;
    // align-items: center;
    // margin-top: 20px;
    // width: 224px;
    padding: 4px;
    border: 1px solid #e6ebf5;
    border-radius: 8px;
    box-shadow: 0px 0px 12px 0px rgba(237, 238, 239, 0.8);

    > div {
      display: inline-block;
      // height: 40px;
      // line-height: 40px;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
    }
    > div:first-child {
      margin-right: 10px;
    }
    .is_active {
      color: #fff;
      transition: all 1s linear;
      background-color: #409eff;
    }
  }
  .form-content {
    margin: 20px 0;
    height: calc(100vh - 300px);
    overflow: auto;
  }
  :deep(.ant-form-item-control-input-content) {
    .ant-input {
      display: block;
      width: 300px;
    }
  }
  :deep(.ant-input-group-wrapper),
  :deep(.ant-select) {
    width: 300px;
  }
  :deep(.ant-input-group-wrapper) {
    .ant-input {
      width: 100%;
    }
  }
  .append-select {
    :deep(.ant-input) {
      width: 80px;
    }
    width: 80px;
  }
  .statusbox {
    margin: 0 10px;
    display: inline-block;
    .statusline {
      padding: 1px;
      padding: 1px;
      background: #67c23a;
      color: #ffffff;
      border-radius: 50%;
      margin-right: 5px;
    }
    .statustxt {
      font-size: 14px;
    }
  }
  .lineBox {
    color: #67c23a;
    .lineed {
      background: #67c23a;
    }
  }
  .unlineBox {
    color: #f56c6c;
    .unline {
      background: #f56c6c;
    }
  }
}
</style>
